package com.example.q_kang.hhh.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;

import com.example.q_kang.hhh.R;
import com.example.q_kang.hhh.home.HomeFragment;
import com.example.q_kang.hhh.login.LoginActivity;
import com.example.q_kang.hhh.message.MessageFragment;
import com.example.q_kang.hhh.order.OrderFragment;
import com.example.q_kang.hhh.setting.SettingFragment;
import com.example.q_kang.hhh.util.MsgViewUtil;
import com.example.q_kang.hhh.util.TipUtil;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.widget.MsgView;
import com.hjq.toast.ToastUtils;
import com.sskj.base.AppUpDateFragment;
import com.sskj.base.MVPActivity;
import com.sskj.base.api.Constant;
import com.sskj.base.api.SpConfig;
import com.sskj.base.base.App;
import com.sskj.base.bean.NoticeBean;
import com.sskj.base.bean.OrderCommmonBean;
import com.sskj.base.bean.UpdataBean;
import com.sskj.base.bean.UserData;
import com.sskj.base.bean.rxbus.MainChangeTabBean;
import com.sskj.base.bean.rxbus.RefreshOrderBean;
import com.sskj.base.entry.TabItem;
import com.sskj.base.rxbus2.RxBus;
import com.sskj.base.rxbus2.Subscribe;
import com.sskj.base.rxbus2.ThreadMode;
import com.sskj.base.utils.APKVersionCodeUtils;
import com.sskj.base.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

public class MainActivity extends MVPActivity<MainPresenter> {
    @BindView(R.id.tabLayout)
    CommonTabLayout tabLayout;

    private int selectPosition;
    private List<Fragment> fragments = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public MainPresenter getPresenter() {
        return new MainPresenter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getOrderCommonData();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        showLoading();
        mPresenter.getNotice();
        mPresenter.getUserData();
        mPresenter.getOrderCommonData();
        mPresenter.updata(APKVersionCodeUtils.getVerName(this));
        fragments.add(HomeFragment.newInstance());
        fragments.add(OrderFragment.newInstance());
        fragments.add(MessageFragment.newInstance());
        fragments.add(SettingFragment.newInstance());
    }

    @Override
    public void initData() {
        initFragment();
        setTabSelection(0);
        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appJavaMainActivity1), R.mipmap.icon_home_yes, R.mipmap.icon_home_no));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appJavaMainActivity2), R.mipmap.icon_order_yes, R.mipmap.icon_order_no));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appJavaMainActivity3), R.mipmap.icon_message_yes, R.mipmap.icon_message_no));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appJavaMainActivity4), R.mipmap.icon_setting_yes, R.mipmap.icon_setting_no));
        tabLayout.setTabData(tabItems);
        tabLayout.setMsgMargin(1, -5, 5);

        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
//                if (position == 1) {
//                    ToastUtils.show(App.INSTANCE.getString(R.string.not_open));
//                    tabLayout.setCurrentTab(selectPosition);
//                    return;
//                }
                setTabSelection(position);
                selectPosition = position;
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    public void initFragment() {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        for (Fragment fragment : fragments) {
            transaction.add(R.id.main_content, fragment);
        }
        transaction.commit();
    }

    public void setTabSelection(int index) {
        // 开启一个Fragment事务
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(fragmentTransaction);
        fragmentTransaction.show(fragments.get(index));
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param fragmentTransaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction fragmentTransaction) {
        for (Fragment fragment : fragments) {
            fragmentTransaction.hide(fragment);
        }
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    public void getUserSuccess(UserData.UserinfoBean userinfo) {
        SPUtils.put(App.INSTANCE, SpConfig.Head, userinfo.getHead());
        if (!TextUtils.isEmpty(userinfo.getZfb_username())) {
            SPUtils.put(App.INSTANCE, SpConfig.ALIPAY, "1");
        }
        if (!TextUtils.isEmpty(userinfo.getWx_username())) {
            SPUtils.put(App.INSTANCE, SpConfig.WECHAT, "1");
        }
        if (!TextUtils.isEmpty(userinfo.getBankNum()) && !userinfo.getBankNum().equals("0")) {
            SPUtils.put(App.INSTANCE, SpConfig.BANK, "1");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeTab(MainChangeTabBean mainTabChange) {
        setTabSelection(mainTabChange.getPos());
        tabLayout.setCurrentTab(1);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshOrder(RefreshOrderBean refreshOrderBean) {
        mPresenter.getOrderCommonData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this);
        }
    }

    public void needUpdata(UpdataBean updataBean) {

        if (updataBean == null) {
            return;
        }
//        if (updataBean.getUptype().equals("2")) {
//            updataBean.isMustUp();
//        }
        String verName = APKVersionCodeUtils.getVerName(this);
        updataBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);
        if (APKVersionCodeUtils.compareVersion(updataBean.getVersion(), verName) == 1) {
            android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, updataBean);
            appUpDateFragment.setArguments(bundle);
            fragmentTransaction.add(appUpDateFragment, "updateUI");
            fragmentTransaction.commitAllowingStateLoss();
        } else {
        }

    }

    public void getOrderDataSucess(OrderCommmonBean orderCommmonBean) {

        if (orderCommmonBean == null) {
            return;
        }
        if (Integer.valueOf(orderCommmonBean.getPdTgbzTwo()) > 0
                || Integer.valueOf(orderCommmonBean.getPdTgbzThree()) > 0
                || Integer.valueOf(orderCommmonBean.getPdJsbzTwo()) > 0
                || Integer.valueOf(orderCommmonBean.getPdJsbzThree()) > 0) {
            MsgView msgView = tabLayout.getMsgView(1);
            MsgViewUtil.show(msgView, 0);
        } else {
            tabLayout.hideMsg(1);
        }
    }

    public void showNoticeDialog(NoticeBean noticeBean) {
        if (noticeBean != null) {
            TipUtil.getNotice(this, noticeBean.getWeb_bomb()).show();
        }
    }
}
